/*
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
 */

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
#if 0
class Solution {
public:
    ListNode *merge2Lists(ListNode *l1, ListNode *l2) {
        //if (!l1) return l2; if (!l2) return l1;
        ListNode head(-1), *ptr = &head;
        while (l1 && l2) {
            if (l1->val <= l2->val) {ptr->next = l1; l1=l1->next;}
            else {ptr->next = l2; l2=l2->next; }
            ptr = ptr->next;
        }
        if (l1) ptr->next = l1;
        if (l2) ptr->next = l2;
        return head.next;
    }
    ListNode *mergeKLists(vector<ListNode *> &lists) {
        ListNode *cur = (lists.size()>0)?lists[0]:NULL;
        for (int i = 0; i < lists.size()-1; i++) {
            cur = merge2Lists(cur, lists[i+1]);
        }
        return cur;
    }
};
#endif

class Solution {
public:
    class mycomparison {
    public:
        bool operator() (const ListNode *lhs, const ListNode *rhs) const
        { return (lhs->val > rhs->val); }
    };
    ListNode *mergeKLists(vector<ListNode *> &lists) {
        if (!lists.size()) return NULL;
        priority_queue<ListNode *, vector<ListNode *>, mycomparison> q;
        for (auto it = lists.begin(); it != lists.end(); it++) {
            if (*it) q.push(*it);
        }
        ListNode head(0), *tail = &head;
        while (!q.empty()) {
            ListNode *min = q.top();
            q.pop(); // remove from queue
            tail = tail->next = min;
            if (tail->next) q.push(tail->next);
        }
        return head.next;
    }
};
